<?php
namespace app\controller;

use app\BaseController;
use app\model\Attendance;
use app\model\FaceRecognition;
use GuzzleHttp\Client;
// use app\controller\ForwardController;
use think\facade\Filesystem;
use think\facade\Log;
//use think\facade\Db;
use think\Request;

//中间件
/* 考勤相关 */

class AttendanceController extends BaseController
{
    public function uploadFace()
    {
        $request = $this->request->param();
        if (isset($request['id'])) {
            $Attendance = Attendance::find($request['id']);
        } else {
            $Attendance = new Attendance;
        }
        foreach ($request as $key => $value) {
            $Attendance->$key = $value;
        }
        $Attendance->update = time();
        $rq = $Attendance->save();
        return success($rq);
    }
    public function delUploadFace(Request $request)
    {
        if ($request->has('deviceId')) {
            $deviceId = $request->param('deviceId');
            $where[] = ['deviceId', '=', $deviceId];
        }else{
            return fail('no deviceId');
        }
        if ($request->has('idCardNumber')) {
            $idCardNumber = $request->param('idCardNumber');
            $where[] = ['idCardNumber', '=', $idCardNumber];
        }else{
            return fail('no idCardNumber');
        }
        
        // $rq = Attendance::destroy(123);
        $rq = Attendance::where($where)->delete();
        if ($rq) {
            return success($request);
        }
    }
    public function addAttendance()
    {
        $request = $this->request->param();
        // 示例用法  

        $FaceRecognition = new FaceRecognition;
        foreach ($request as $key => $value) {
            $FaceRecognition->$key = $value;
        }
        $rq = $FaceRecognition->save();
        $forwardarray = [13081170, 13060875, 13060879, 13060877, 13060878, 13060876, 13060882, 13060880, 13060883, 13060874, 13060881, 13081171, 13081200, 13081202, 13081181, 13081180, 13081198, 13071042, 13111491, 13101345, 13101346, 13101344, 13101349, 13101350, 13101348, 13101349];
        if (in_array($request['deviceId'], $forwardarray)) {
            $cases = [
                13081170 => 1,
                13060875 => 1,
                13060879 => 1,
                13060877 => 1,
                13060878 => 1,
                13060876 => 1,
                13060882 => 1,
                13060880 => 1,
                13060883 => 1,
                13060874 => 1,
                13081171 => 1,
                13081200 => 1,
                13081202 => 1,
                13081181 => 1,
                13081180 => 1,
                13081198 => 1,
                13071042 => 1,
                13111491 => 1,
                13060881 => 1,
                13101345 => 2,
                13101346 => 2,
                13101344 => 2,
                13101349 => 2,
                13101350 => 2,
                13101348 => 2,
                13101349 => 2,
                14031743 => 3,
            ];
            $case = $cases[$request['deviceId']];
            $this->forwardFace($request, $case);
        }
        return success($rq);
    }
    public function getFaceImg(Request $request)
    {

        $where = [];
        if ($request->has('deviceId')) {
            $deviceId = $request->param('deviceId');
            $where[] = ['deviceId', '=', $deviceId];
        } else {
            return fail(null, '缺少必要参数');
        }
        if ($request->has('workerId')) {
            $workerId = $request->param('workerId');
            $where[] = ['workerId', '=', $workerId];
        }
        if (!$request->param('page')) {
            $face_url = FaceRecognition::where($where)->field('id,workerId,name,url,create_time,direction')->order('id desc')->select();
            return success($face_url);
        }
        $face_url = FaceRecognition::where($where)->field('id,workerId,name,url,create_time,direction')->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        return pageReturn($face_url);
    }
    public function getStaffInfo(Request $request)
    {

        $where = [];
        if ($request->has('deviceId')) {
            $deviceId = $request->param('deviceId');
            $where[] = ['deviceId', '=', $deviceId];
        } else {
            return fail(null, '缺少必要参数');
        }
        if (!$request->param('page')) {
            $face_url = Attendance::where($where)->field('id,name,workerId,photo,deviceId')->select();
            return success($face_url);
        }
        $face_url = Attendance::where($where)->field('id,name,workerId,photo,deviceId')->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        return pageReturn($face_url);
    }
    public function uploadFaceImg(Request $request)
    {
        //public/storage/png/2022_07_08/16572664121.png
        $upload_url = env('UPLOAD_URL', true);
        $file = request()->file('file');
        $size = $file->getSize(); //文件大小
        if ($size > 1000000) {
            return fail(null, '请上传小于1M的图片');
        }
        //$文件名
        $fileName = $file->getOriginalName();
        $date = date('Y_m_d', time()); //当天日期
        $fileOssName = time() . $fileName; //阿里云文件名
        $ext = $file->getOriginalExtension(); //文件扩展名
        // $ossurl = config('filesystem.disks.aliyun.url');
        // 上传本地服务器
        $res = Filesystem::disk('public')->putFileAs('face/' . $date, $file, $fileOssName); //按照文件类型分类
        $res = stripslashes($res); //去除转义字符
        $fileurl = 'http://' . $upload_url . '/' . $res;
        return success($fileurl);
    }
    public function yunwangUploadFaceImg(Request $request)
    {
        $post = request()->param('AuthResult');
        Log::write($post, 'face');
        //public/storage/png/2022_07_08/16572664121.png
        $upload_url = env('UPLOAD_URL', true);
        $file = request()->file('AuthPicture');

        $size = $file->getSize(); //文件大小
        // if ($size > 100000) {
        //     return fail(null, '请上传小于100k的图片');
        // }
        //$文件名
        $fileName = $file->getOriginalName();

        // $mb_convert_encoding=mb_convert_encoding($post, "UTF-8", "auto");

        // $AuthResult =json_decode($mb_convert_encoding,true);
        $post = iconv('GB2312', 'utf-8', $post);
        $AuthResult = json_decode($post, true);
        Log::write($AuthResult, 'face');
        $UserName = mb_convert_encoding($AuthResult['UserName'], "UTF-8", "auto");
        // $UserName = iconv('GB2312','utf-8',$AuthResult['UserName']);

        $date = date('Y_m_d', time()); //当天日期
        $fileOssName = time() . $fileName; //阿里云文件名
        $ext = $file->getOriginalExtension(); //文件扩展名
        // $ossurl = config('filesystem.disks.aliyun.url');
        // 上传本地服务器
        $res = Filesystem::disk('public')->putFileAs('face/' . $date, $file, $fileOssName); //按照文件类型分类
        $res = stripslashes($res); //去除转义字符
        $fileurl = 'http://' . $upload_url . '/' . $res;

        $FaceRecognition = new FaceRecognition;
        $FaceRecognition->url = $fileurl;
        $FaceRecognition->fileName = $fileName;
        $FaceRecognition->name = $UserName;
        $FaceRecognition->sid = $AuthResult['UserId'];
        $rq = $FaceRecognition->save();
        return success($fileurl);
    }
    public function yunwangFaceHeart(Request $request)
    {
        $post = request()->param();
        // Log::write($post, 'face');
        $issued = Attendance::where('issued', 1)->select();
        if ($issued) {

            /*
            {
            "CurrentNumber":1,
            "UserId":"12",
            "UserName":"张三"
            "Cidentitynumber":”321212312233"，
            "CertificateNumber":”321212312233"，
            "PassWord":"123456"
            "UrlAddress":"http://www.baidu.com/myPicture.jpg"
            }，
             */
            foreach ($issued as $key => $value) {
                $return[$key]['CurrentNumber'] = $key + 1;
                $return[$key]['UserId'] = $value->workerId;
                $return[$key]['UserName'] = $value->name;
                $return[$key]['Cidentitynumber'] = $value->idCardNumber;
                $return[$key]['CertificateNumber'] = $value->idCardNumber;
                $return[$key]['PassWord'] = 0;
                $return[$key]['UrlAddress'] = $value->photo;
            }
            $return['msgid'] = time() . rand(100, 999);
            $return['deviceNo'] = 123456;
            $return['OperationCmd'] = 1;
            $return['TotalNumber'] = $issued->count();
            // Attendance::where('issued', 1)->update(['issued' => 0]);
            return json($return);
        }
    }
    /* 外采人脸设备-init初始化配置请求 */
    public function init(Request $request)
    {
        $request = $this->request->param();
        Log::write($request, 'face');
        $FaceRecognition = FaceRecognition::where('deviceId', $request['deviceId'])->find();
        if (!$FaceRecognition) {
            $FaceRecognition = new FaceRecognition;
        }
        foreach ($request as $key => $value) {
            $FaceRecognition->$key = $value;
        }
        $rq = $FaceRecognition->save();
        $re = [
            'success' => true,
            'code' => 0,
            'message' => "success",
            'time' => time(),
            'data' => [
                'dgBaseInfo' => json([]),
                'setting' => json([]),
            ],
            'event' => "init",
        ];
        return json($re);
    }
    /* 外采人脸设备-下载白名单 */
    public function workers(Request $request)
    {
        $request = $this->request->param();
        Log::write($request, 'face');
        $FaceRecognition = Attendance::where('deviceId', '=', $request['deviceId'])->field('update,name,idCardNumber,workerId,photo')->select();

        $re = [
            'success' => true,
            'code' => 0,
            'message' => "success",
            'time' => time(),
            'data' => $FaceRecognition,
            'event' => "workers",
        ];
        return json($re);
    }
    /* 外采人脸设备-考勤照片上传 */
    public function photo(Request $request)
    {
        $request = $this->request->param();
        Log::write($request, 'face');
        $image = $request['base64'];
        // $image = "data:image/jpg;base64," . $base64;
        $imageName = 'face' . time() . '.jpg';
        // if (strstr($image, ",")) {
        //     $image = explode(',', $image);
        //     $image = $image[1];
        // }
        $path = "storage/faceEquipment/";
        if (!is_dir($path)) { //判断目录是否存在 不存在就创建
            mkdir($path, 0777, true);
        }
        $imageSrc = $path . "/" . $imageName; //图片名字
        //地址存入数据库
        // $upload = new UploadFile;
        // $upload->url = env('UPLOAD_URL', true) . '/other/qrcode/' . $imageName;
        // $upload->filename = $imageName;
        // if (isset($post['type'])) {
        //     $upload->type = $post['type'];
        // }
        // $upload->save();
        $r = file_put_contents($imageSrc, base64_decode($image)); //返回的是字节数
        $url = env('UPLOAD_URL', true) . '/faceEquipment/' . $imageName;

        $FaceRecognition = new FaceRecognition;
        $name = Attendance::where('deviceId', $request['deviceId'])->value('name');
        $FaceRecognition->url = $url;
        $FaceRecognition->fileName = $imageName;
        $FaceRecognition->name = $name;
        $FaceRecognition->deviceId = $request['deviceId'];
        $FaceRecognition->workerId = $request['workerId'];
        $FaceRecognition->direction = $request['direction'];

        $rq = $FaceRecognition->save();
        $re = [
            'success' => true,
            'code' => 0,
            'message' => "success",
            'time' => time(),
            'data' => [
                'path' => $url,
            ],
            'event' => "photo",
        ];
        return json($re);
    }
    //人脸转发
    public function forwardFace($data, $case)
    {
        switch ($case) {
            case 1:
                //鼎力兴-德州平台对接-袁
                $param = Attendance::where('name', $data['name'])->find();
                // die($param);
                $url = 'http://222.133.41.47:8090/XHTAPI/api/ZHGD_API';
                /* 数据 */
                $paramJsonData = [
                    "xhtProjID" => (int) $param['pid'],
                    "Date" => date('Y-m-d H:i:s', time()),
                    "ImageURL" => $data['url'],
                    "RYID" => $param['workerId'],
                ];
                $send = [
                    "ApiKey" => 'ae5992c5-e8e7-421c-8157-3a5ac08e8cdd',
                    "FunctionName" => 'Xht_AddTowerWorkerAttendanceFac',
                    "paramJsonData" => $paramJsonData,
                ];
                $client = new Client;
                $response = $client->request('POST', $url, [
                    'json' => $send,
                ])->getBody();
                $stringBody = (string) $response;
                // Log::write($send, 'addAttendance_1');
                // Log::write($stringBody, 'addAttendance_1');
                break;
            case 2:
                //国础塔吊技术对接群
                $param = Attendance::where('name', $data['name'])->find();
                $url = 'https://zhcs.zhnbxc.top:18090/admin-api/system/api/tower/attendance';
                $send = [
                    "attendanceTime" => date('Y-m-d H:i:s', time()),
                    "deviceId" => $param->deviceId,
                    "name" => $param->name,
                    "photo" => $data['url'],
                    "workerId" => $param->workerId,
                ];
                $client = new Client;
                $response = $client->request('POST', $url, [
                    'json' => $send,
                ])->getBody();
                $stringBody = (string) $response;
                // Log::write($send, 'addAttendance_1');
                // Log::write($stringBody, 'addAttendance_1');
                break;
            case 3:
                //江苏安快
                $imageUrl = 'https://example.com/path/to/image.jpg';  
                $base64Image = $this->imageToBase64($imageUrl);
                $param = Attendance::where('name', $data['name'])->find();
                $url = 'http://123.60.57.233:8082/ayy/api/driver';
                $send = [
                    "sendTime" => date('Y-m-d H:i:s', time()),
                    "deviceId" => $param->deviceId,
                    "name" => $param->name,
                    "photo" => $base64Image,
                    "runStatus" => 1,
                    "idCard" => '',
                ];
                $client = new Client;
                $response = $client->request('POST', $url, [
                    'json' => $send,
                ])->getBody();
                $stringBody = (string) $response;
                // Log::write($send, 'addAttendance_1');
                // Log::write($stringBody, 'addAttendance_1');
                break;
            default:
                # code...
                break;
        }
    }
    public function imageToBase64($url)
    {
        // 初始化一个 cURL 句柄
        $ch = curl_init();

        // 设置 cURL 选项
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

        // 执行 cURL 请求并获取响应
        $imageData = curl_exec($ch);

        // 检查是否有错误发生
        if (curl_errno($ch)) {
            $error_msg = curl_error($ch);
            return "cURL Error: " . $error_msg;
        }

        // 关闭 cURL 句柄
        curl_close($ch);

        // 将图片数据转换为 Base64 编码
        $base64Data = 'data:image/jpeg;base64,' . base64_encode($imageData);
        // $base64Data = base64_encode($imageData);

        return $base64Data;
    }

}
class Issued
{
}
